package grimbo.goodwinfooty;

import grimbo.goodwinfooty.service.model.FootyMatrix;
import grimbo.goodwinfooty.service.model.Game;
import grimbo.goodwinfooty.service.model.Player;
import grimbo.goodwinfooty.service.model.PlayerPayment;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringEscapeUtils;

public class FootyMatrixToSQL {
	private FootyMatrix fm;
	private OutputStream out;
	private PrintWriter pw;

	public FootyMatrixToSQL(FootyMatrix fm, OutputStream out) {
		this.fm = fm;
		this.out = out;
	}

	public void convert() throws IOException {
		pw = new PrintWriter(new OutputStreamWriter(out));

		for (int i = 0; i < fm.getPlayers().size(); i++) {
			Player p = fm.getPlayer(i);
			convert(p);
		}

		for (int i = 0; i < fm.getGames().size(); i++) {
			Game g = fm.getGame(i);
			convert(g);
		}

		pw.flush();
	}

	private void convert(Player p) {
		Object[] args = new Object[] { String.valueOf(p.getId()),
				StringEscapeUtils.escapeSql(p.getName()),
				String.valueOf(p.getInheritedDebt()) };
		String s = MessageFormat.format(
				"insert into player values ({0}, ''{1}'', {2});", args);
		pw.println(s);
	}

	private void convert(Game g) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sDate = sdf.format(g.getDate());
		Object[] args = new Object[] { String.valueOf(g.getId()), sDate,
				String.valueOf(g.getPrice()) };
		String s = MessageFormat.format(
				"insert into game values ({0}, ''{1}'', {2});", args);
		pw.println(s);
		for (int i = 0; i < g.getPayments().size(); i++) {
			PlayerPayment pp = g.getPayment(i);
			convert(pp, g);
		}
	}

	private void convert(PlayerPayment pp, Game g) {
		Object[] args = new Object[] { String.valueOf(g.getId()),
				String.valueOf(pp.getPlayer().getId()),
				String.valueOf(pp.getPayment()), pp.isCharged() ? "1" : "0" };
		String s = MessageFormat
				.format(
						"insert into player_payment values ({0}, {1}, {2}, {3});",
						args);
		pw.println(s);
	}
}
